<template>
  <view class="container">
    <u-tabs @change="changeTab" :list="tabList" :current="currentTab" lineColor="#8F4C38" lineWidth="70px"></u-tabs>
    <view
        class="content-container"
        @touchstart="onTouchStart"
        @touchmove="onTouchMove"
        @touchend="onTouchEnd"
    >
      <view
          class="tab-content"
          :style="{ transform: `translateX(${(dragOffset - currentTab * 100)}%)`, transition: dragTransition }"
      >
        <view class="tab-pane" v-for="(tab, index) in tabList" :key="index">
          <!-- 每个 tab 的内容 -->
          <view v-if="forward.length">
            <view class="message-item" v-for="(msg, idx) in forward" :key="idx">
              <view class="msg-header">
                <view class="msg-title">{{ msg.reasonType }}</view>
                <view class="progress" :style="{ color: msg.progress? '#FF4D4F' : '#c96344' }">
                  {{msg.handlerStatusStr}}
                </view>
<!--                <view class="toggle-btn" @click="toggleExpand(idx)">-->
<!--                  {{ msg.isExpand ? '▲' : '▼' }}-->
<!--                </view>-->
                <img class="chapter-arrow-img" @click.stop="toggleExpand(idx)" :class="{ open:  msg.isExpand }" src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/zhanKaiMe.png" />

              </view>
              <view class="msg-content-wrapper">
                <view
                    class="msg-content"
                    :class="{ 'slide-down': msg.isExpand }"
                >
                  <view class="msg-text">{{ msg.reasonText }}</view>
                  <view style="color: #8F4C38;margin-top: 40rpx">处理详情</view>
                  <view style="padding: 0 40rpx;color: #4B5563;">
                    {{msg.handleResult?msg.handleResult:'处理中...'}}
                  </view>
                </view>
                <view class="msg-time" v-if="msg.createTime">{{ msg.createTime.substr(0, 10) }}</view>
              </view>
            </view>
          </view>
          <view v-else style="width: 100%;text-align: center;color: #6B7280;margin-top: 100px">
            暂时还没有记录哦
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {getFeedbackList} from "../../api/new";
export default {
  name:"complaintList",
  data() {
    return {
      tabList: [
        {name: '待处理'}, {name: '已完成'}
      ],
      currentTab: 0,
      startX: 0,
      dragOffset: 0,
      dragTransition: 'transform 0.3s ease',
      threshold: 50, // 滑动阈值（像素）
      propagation:{
        limit:10,
        page:1,
        complete:false
      },
      list:[{},{}],
      forward:[]
    };
  },
  onLoad(options) {
    if (options.index !== undefined && !isNaN(options.index)) {
      this.currentTab = parseInt(options.index);
      this.currentTab = Math.max(0, Math.min(this.currentTab, this.tabList.length - 1));
    }
  },
  methods: {
    changeTab(e) {
      this.currentTab = e.index;
    },
    toggleExpand(index) {
      this.forward[index].isExpand = !this.forward[index].isExpand;
      this.$forceUpdate()
      },

    // 滑动手势处理
    onTouchStart(e) {
      this.startX = e.touches[0].clientX;
      this.lastTouchX = e.touches[0].clientX;
      this.touchStartTime = Date.now();
      this.dragOffset = 0;
      this.dragTransition = 'none';
      this.touchMoves = [];
    },
    onTouchMove(e) {
      const moveX = e.touches[0].clientX - this.startX;
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      // 记录触摸移动轨迹（用于防抖）
      this.touchMoves.push(moveX);
      if (this.touchMoves.length > 5) this.touchMoves.shift();
      // 防抖判断：如果最近5次移动距离变化不大，视为抖动，直接返回
      if (this.touchMoves.length >= 5 && Math.abs(this.touchMoves[4] - this.touchMoves[0]) < 10) {
        return;
      }
      // 增加最小移动阈值，避免轻微触碰触发
      const threshold = 60;
      if (Math.abs(moveX) < threshold) return;
      // 计算拖动百分比
      let dragPercentage = (moveX / windowWidth) * 100;
      // 禁止边界拖动
      if ((this.currentTab === 0 && dragPercentage > 0) || (this.currentTab === this.tabList.length - 1 && dragPercentage < 0)) {
        dragPercentage = 0;
      }
      this.dragOffset = dragPercentage;
    },
    onTouchEnd() {
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      const moveX = this.dragOffset * windowWidth / 100;
      const touchDuration = Date.now() - this.touchStartTime;
      const touchDistance = Math.abs(moveX);
      // 计算滑动速度（像素/毫秒）
      const swipeSpeed = touchDistance / touchDuration;
      // 确保动画时间一致
      const animationDuration = 300;
      this.dragTransition = `transform ${animationDuration}ms cubic-bezier(0.0, 0.0, 1.0, 1.0)`;
      // 动态阈值计算（根据滑动速度调整，速度越快阈值越低）
      const baseThreshold = windowWidth / 5;
      const speedFactor = Math.min(1, swipeSpeed * 2);
      const dynamicThreshold = baseThreshold * (1 - speedFactor * 0.5);
      // 快速滑动判断
      const isQuickSwipe = (touchDuration < 300 && touchDistance > windowWidth * 0.1) || (swipeSpeed > 0.5);
      let targetTab = this.currentTab;
      if ((moveX > dynamicThreshold && this.currentTab > 0) || (isQuickSwipe && moveX > 0 && this.currentTab > 0)) {
        targetTab--;
      } else if ((moveX < -dynamicThreshold && this.currentTab < this.tabList.length - 1) || (isQuickSwipe && moveX < 0 && this.currentTab < this.tabList.length - 1)) {
        targetTab++;
      }
      targetTab = Math.max(0, Math.min(this.tabList.length - 1, targetTab));
      if (targetTab !== this.currentTab) {
        this.currentTab = targetTab;
      }
      setTimeout(() => {
        this.dragOffset = 0;
        this.dragTransition = 'none';
      }, animationDuration);
    },
    getList(newVal){
      if(newVal!=undefined){
        if(newVal===0) {
          this.propagation.complete=false;
        } else {
          this.propagation.complete=true;
        }
      }
      getFeedbackList(this.propagation).then(res=>{
        if (this.propagation.page === 1) {
          this.list[this.currentTab]=res.data
          this.forward=this.list[this.currentTab].list
        } else {
          this.list[this.currentTab].list = [...this.list[this.currentTab].list, ...res.data.list];
          this.forward=this.list[this.currentTab].list
        }
        console.log(this.forward)
        this.list[this.currentTab].page=res.data.page+1
      })
    },
  },
  onReachBottom(){
    this.getList(this.currentTab)
  },
  onShow () {
    this.getList(this.currentTab)
  },
  watch: {
    // 监听currentTab变化
    currentTab(newVal) {
      if(Object.keys(this.list[newVal]).length!==0){
        this.forward=this.list[newVal].list
      }else{
        this.getList(newVal);
      }
    }
  },
};
</script>

<style lang="scss" scoped>
// 定义变量
$container-padding: 15px;
$message-padding: 10px;
$border-radius: 10px;
$transition-time: 0.3s;
$tab-height: 100rpx;
.chapter-arrow-img {
  width: 18px;
  height: 18px;
  margin-left: 6px;
  transition: transform 0.2s;
  display: inline-block;
  transform: rotate(180deg);
  &.open {
    transform: rotate(360deg);
  }
}
.container {
  height: 100vh;
  overflow: hidden;

  .content-container {
    width: 100%;
    height: calc(100vh - #{$tab-height}); // 使用变量计算高度
    overflow: hidden;
    position: relative;

    .tab-content {
      display: flex;
      height: 100%;

      .tab-pane {
        flex-shrink: 0;
        width: 100%;
        height: 100%;
        overflow-y: auto;
        padding: 0 $container-padding;

        .message-item {
          background-color: #fff;
          padding: $message-padding;
          border-radius: $border-radius;
          margin-top: 10px;

          // 使用嵌套结构
          .msg-header {
            display: flex;
            align-items: center;
            position: relative;
            .msg-title {
              //font-size: 20px;
              color: #FF4D4F;
              background-color: #ffd1d1;
              border: 1px solid #FF4D4F;
              border-radius: 10px;
              padding: 2rpx 6rpx;
            }
            .progress{
              position: absolute;
              right: 40rpx;

            }
            .toggle-btn {
              color: #8F4C38;
              font-size: 30rpx;
              position: absolute;
              right: 0;
            }
          }

          .msg-content-wrapper {
            overflow: hidden;
            transition: all $transition-time ease-in-out;
            .msg-text{
              color: #4B5563;
              min-height: 84rpx;
            }

            .msg-time {
              color: #a7a7a7;
              font-size: 22rpx;
              margin-top: 20rpx;
            }
          }

          .msg-content {
            max-height: 84rpx;
            opacity: 0.85;
            overflow: hidden;
            padding-top: 8px;
            padding-bottom: 0;
            transition: all 0.4s cubic-bezier(.55,0,.1,1);
          }
          .msg-content.slide-down {
            max-height: 1000px;
            opacity: 1;
            padding-bottom: 8px;
          }
        }
      }
    }
  }
}
</style>